const { querySQL } = require('../db/mysql')
const xss = require('xss')

// 获取博客列表
const getList = (author, keyword) => {
  
  let sql = `select * from blogs where 1=1 `
  if (author) {
    sql += `and author='${author}' `
  }
  if (keyword) {
    sql += `and title like '%${keyword}%' `
  }
  sql += `order by createtime desc;`
  console.log('getList-sql', sql, querySQL(sql))
  return querySQL(sql)
}

// 获取博客详情
const getDetail = (id) => {
  const sql = `select * from blogs where id='${id}'`
  return querySQL(sql).then(rows => {
    console.log('getDetail-rows', rows)
    return rows[0]
  })
}

// 新建博客
const newBlog = (blogData = {}) => {
  const title = xss(blogData.title) // 使用xss转义，防止XSS攻击
  const content = xss(blogData.content) // 使用xss转义，防止XSS攻击
  const author = blogData.author
  const createTime = new Date().getTime()

  const sql = `
    insert into blogs (title, content, author, createtime)
    values ('${title}', '${content}', '${author}', '${createTime}')
  `

  return querySQL(sql).then(insertData => {
    console.log('insertData', insertData)
    return {
      id: insertData.insertId
    }
  })
}

// 更新博客
const updateBlog = (id, blogData = {}) => {
  const title = xss(blogData.title) // 使用xss转义，防止XSS攻击
  const content = xss(blogData.content) // 使用xss转义，防止XSS攻击

  const sql = `update blogs set title = '${title}', content = '${content}' where id = ${id}`

  return querySQL(sql).then(data => {
    console.log('updateBlog', data)
    if (data.affectedRows > 0) {
      return true
    } else {
      return false
    }
  })
}

// 删除博客
const delBlog = (id, author) => {
  const sql = `delete from blogs where id = ${id} and author = '${author}';`
  console.log('sql', sql)
  return querySQL(sql).then(data => {
    console.log('delBlog', data)
    if (data.affectedRows > 0) {
      return true
    } else {
      return false
    }
  })
}

module.exports = {
  getList,
  getDetail,
  newBlog,
  updateBlog,
  delBlog
}